<script lang="ts">
import type { PwaBonusDataType, SignUpBonusDataType } from '../ts/depositBonusInfoHook';
import Countdown from '~/pages/promo/pack/components/Countdown.vue';
import signupBonusIcon from '../icon/signup-bonus-icon.svg';
import { usePwaBonusInfo, useSignUpBonusInfo, useWelcomeBonusInfo } from '../ts/depositBonusInfoHook';
import { getMaxRateText, toBnInt, toDecimalPlaces } from '../ts/utils';

export type BonusKeyType = 'welcome' | 'signUp' | 'pwa';
</script>

<script setup lang="ts">
const props = defineProps<{
  currency: string;
  hieednBottomLine?: boolean;
  decimals?: number;
  bnMin?: ReturnType<typeof bignumber>;
  bnMax?: ReturnType<typeof bignumber>;
  isFiat?: boolean;
  checkedBonusKey?: BonusKeyType;
}>();

const bonusKeyRef = defineModel<BonusKeyType | undefined>('bonusKey', { default: void 0 });

const welcomeBonusLenRef = defineModel('welcomeBonusLen', { default: 0 });

const getCurrencyRef = computed(() => props.currency || '');

const {
  getWelcomeBonusRef,
  getAvailableRef,
  getTimeInfoRef,
  getBonusesDetailsRef,
  // getBonusDetailDataRef,
  refetchDepositReady,
} = useWelcomeBonusInfo(getCurrencyRef);

const { getSignUpBonusDataRef } = useSignUpBonusInfo(false, getCurrencyRef);

const { getPwaBonusDataRef } = usePwaBonusInfo(false, getCurrencyRef);

const detailsColors = [
  'from-[#D64747] to-[#6F2F2F] bg-gradient-to-r',
  'from-[#FACC15] to-[#D97706] bg-gradient-to-r',
  'from-[#98D4FA] to-[#1671AF] bg-gradient-to-r',
];

const getListRef = computed(() => {
  if (!getAvailableRef.value || !getTimeInfoRef.value.isInTime) {
    return [];
  }
  const { bnMin, bnMax } = props;
  const list = getBonusesDetailsRef.value.map((x, idx) => ({ ...x, className: detailsColors[idx < 3 ? idx : idx % 3], amountProps: getAmountProps(x, 'bnDepositAmount', 'usdText') }));
  if ((!bnMin && !bnMax) || (bnMin?.lte(0) && bnMax?.lte(0))) {
    return list;
  }
  return list.filter((x) => {
    if ((bnMin?.gt(0) && bnMin?.gt(x.amountProps.bnVal)) || (bnMax?.gt(0) && x.amountProps.bnVal.gt(bnMax))) {
      return false;
    }
    return true;
  });
});

watch(getListRef, (v) => {
  welcomeBonusLenRef.value = v.length;
}, { immediate: true });

type AmountItemType = GetArrayItemType<typeof getBonusesDetailsRef.value> | SignUpBonusDataType | PwaBonusDataType;

function getAmountProps<T extends AmountItemType>(item: T, bnAmountKey: keyof T, textKey: keyof T, dec?: number) {
  const bnV = item?.[bnAmountKey as keyof AmountItemType] || bignumber(0);
  const _dec = dec || props.decimals || 0;
  const bnVal = props.isFiat ? toBnInt(bnV) : toDecimalPlaces(bnV, false, _dec < 3 ? 2 : dec);
  const show = bnVal.gt(0);
  return { show, text: show ? bnVal.toFormat() : item?.[textKey as keyof AmountItemType], bnVal };
}

const getSignUpBonusAmountProps = computed(() => {
  const data = getSignUpBonusDataRef.value;
  if (!data)
    return null;
  return {
    amount: getAmountProps(data, 'bnAmount', 'amountUsdText'),
    minDeposit: getAmountProps(data, 'bnDepositAmount', 'depositUsdText'),
  };
});

const getPwaBonusAmountProps = computed(() => {
  const data = getPwaBonusDataRef.value;
  return data ? getAmountProps(data, 'bnAmount', 'amountUsdText', 4) : null;
});

const getMaxBoostRateTextRef = computed(() => getMaxRateText(getListRef.value.map(x => x.bnBoostRate || bignumber(0))));

const countDownFinishInfo = reactive<Record<BonusKeyType | 'welcomeTop', boolean>>({
  welcomeTop: false,
  welcome: false,
  signUp: false,
  pwa: false,
});

async function onCountDownFinish(key: BonusKeyType | 'welcomeTop') {
  countDownFinishInfo[key] = true;
  await refetchDepositReady();
  const findKey = findSelectedKey();
  if (findKey && selectBonusKeyRef.value && findKey !== selectBonusKeyRef.value) {
    changeRadioFn(findKey, true);
  }
}

const getIsShowMapRef = computed(() => {
  const showMap: Record<BonusKeyType, boolean> = {
    welcome: getListRef.value.length > 0 && !countDownFinishInfo.welcome,
    signUp: !!getSignUpBonusDataRef.value?.available && !countDownFinishInfo.signUp,
    pwa: !!getPwaBonusDataRef.value?.available && !countDownFinishInfo.pwa,
  };
  const len = Object.keys(showMap).map(k => showMap[k as BonusKeyType]).filter(x => x).length;
  return {
    ...showMap,
    welcomeTop: showMap.welcome && !countDownFinishInfo.welcomeTop && getTimeInfoRef.value.isInBoostExpireSecond,
    bottomTips: len > 1,
  };
});

// function openBonusPoup() {
//   const detailData = getBonusDetailDataRef.value;
//   if (getListRef.value.length > 0 && detailData) {
//     globalPopups?.welcomeBonusPopup?.open({ ...props, detailData: { ...detailData, bonusesDetails: getListRef.value } });
//   }
// }
interface BonusDataType { data?: { available?: boolean | null; checked?: boolean | null }; key: BonusKeyType ; hidden?: () => boolean };

function findSelectedKey() {
  const list: BonusDataType[] = [
    { data: getPwaBonusDataRef.value, key: 'pwa' },
    { data: getWelcomeBonusRef.value, key: 'welcome', hidden: () => !getListRef.value.length },
    { data: getSignUpBonusDataRef.value, key: 'signUp' },
  ];
  for (const item of list) {
    if (item.hidden?.()) {
      continue;
    }
    if (item?.data?.available && item?.data?.checked) {
      return item.key;
    }
  }
  return void 0;
}

const selectBonusKeyRef = ref<BonusKeyType | undefined>();

const getCheckedRef = computed((): Record<BonusKeyType, boolean> => {
  const key = selectBonusKeyRef.value;
  return {
    welcome: key === 'welcome',
    signUp: key === 'signUp',
    pwa: key === 'pwa',
  };
});

function changeRadioFn(key?: BonusKeyType, reqApi = true) {
  if (key) {
    selectBonusKeyRef.value = key;
    bonusKeyRef.value = key;
    reqApi && updateActivityCode(key);
  }
}

const isInitRef = ref(true);

async function initSelectBonusKey() {
  try {
    const checkKey = props.checkedBonusKey;
    const findKey = findSelectedKey();
    changeRadioFn(findKey, false);
    if (checkKey && findKey && findKey !== checkKey) {
      await refetchDepositReady();
      changeRadioFn(checkKey, true);
      if (checkKey === 'welcome' && !getListRef.value.length) {
        changeRadioFn(findSelectedKey(), true);
      }
    }
    isInitRef.value = false;
  }
  catch (error) {
    isInitRef.value = false;
  }
}

initSelectBonusKey();

const activityCodeMut = useMutation({
  mutationKey: [apis.apiFundDepositChangeActivity.id],
  mutationFn: apis.apiFundDepositChangeActivity.setDefaultConfig({ successMessage: false, errorMessage: true }),
  onSuccess() {
    refetchDepositReady();
  },
});

function updateActivityCode(key: BonusKeyType) {
  const codes: Record<BonusKeyType, string> = {
    welcome: getWelcomeBonusRef.value?.activity_code || '',
    signUp: getSignUpBonusDataRef.value?.activity_code || '',
    pwa: getPwaBonusDataRef.value?.activity_code || '',
  };
  if (!codes[key] || activityCodeMut.isPending.value) {
    return;
  }
  activityCodeMut.mutate({ requestBody: { activity_code: codes[key] } });
}

// function openSignUpBonusPoup() {
//   globalPopups?.signUpBonusPopup?.open({ detailData: getSignUpBonusDataRef.value });
// }

defineExpose({ setRadio: changeRadioFn });
</script>

<template>
  <div class="grid grid-cols-1 gap-3">
    <div
      v-if="!isInitRef && getIsShowMapRef.welcomeTop && getCheckedRef.welcome"
      class="flex items-center whitespace-normal break-words break-all rounded-lg from-[#DE1212] to-[#AF0E0E] bg-gradient-to-r px-3 py-2.5 text-sys-text-head"
    >
      <span class="lt-mobile:max-w-[47vw]">{{ $t('a7RkeDkR9aDTjMg1Woky') }}</span>
      <div class="w-40 flex items-center lt-mobile:w-[unset]">
        <i class="i-local:bonus__card-icon mx-1 h-4.5 w-4.5 shrink-0" />
        <span class="font-semibold">{{ getMaxBoostRateTextRef }}</span>
        <div class="divider-v-gradual-white" />
        <Countdown
          :value="getTimeInfoRef.boostExpireDate"
          itemClassName="rounded-1 px-1 py-[1px] bg-red-800 text-[13px] text-sys-text-head"
          hiddenTopText
          @finish="onCountDownFinish('welcomeTop')"
        />
        <!-- <i v-if="getBonusDetailDataRef" class="i-ri:question-line ml-1.5 mt-0.5 h-4.5 w-4.5 shrink-0 cursor-pointer" @click="openBonusPoup" /> -->
      </div>
    </div>

    <TSkeleton v-if="isInitRef && getIsShowMapRef.welcome">
      <TSkeleton type="rect" width="auto" />
    </TSkeleton>
    <div
      v-else-if="getIsShowMapRef.welcome"
      class="grid grid-cols-1 gap-1.5 rounded-lg bg-sys-layer-a p-3"
    >
      <ARadio :checked="getCheckedRef.welcome" class="check-box" @change="changeRadioFn('welcome')">
        <span class="text-sys-text-head font-semibold">{{ $t('4KxTr6D4MkAv8PyKos92') }}</span>
      </ARadio>

      <div v-if="getCheckedRef.welcome">
        <div v-for="(item, idx) of getListRef" :key="idx" class="flex gap-1 whitespace-normal break-words break-all rounded-lg">
          <div class="mt-1 h-3 w-3 shrink-0 rounded-[50%]" :class="item.className" />
          <I18nT keypath="zRMCwPsEbNiNgIz2wEqa" tag="div" class="flex-1 text-sys-text-body">
            <template #amount>
              <TCurrencyIcon v-if="item.amountProps.show" class="ml-1" :symbol="currency" size="14px" />
              <span class="mx-1 text-sys-text-head font-semibold">{{ item.amountProps.text }}</span>
            </template>
            <template #rate>
              <span class="mx-1">
                <span v-if="getTimeInfoRef.isInBoostExpireSecond" class="mr-1 text-sys-text-head">{{ item.boostRateText }}</span>
                <span
                  :class="{
                    'text-sys-text-head font-semibold': !getTimeInfoRef.isInBoostExpireSecond,
                    'text-sys-text-body font-semibold line-through decoration-red': getTimeInfoRef.isInBoostExpireSecond,
                  }"
                >{{ item.bonustRateText }}</span>
              </span>
            </template>
          </I18nT>
        </div>
      </div>

      <AStatisticCountdown class="!hidden" :value="getTimeInfoRef.expireDate" @finish="onCountDownFinish('welcome')" />
    </div>

    <TSkeleton v-if="isInitRef && getIsShowMapRef.signUp">
      <TSkeleton type="rect" width="auto" />
    </TSkeleton>

    <div v-else-if="getIsShowMapRef.signUp" class="rounded-lg bg-sys-layer-a p-3">
      <ARadio :checked="getCheckedRef.signUp" class="check-box" @change="changeRadioFn('signUp')">
        <span class="text-sys-text-head font-semibold">{{ $t('gbVGtpxAsEaO0Ib3BFvrY') }}</span>
      </ARadio>
      <div v-if="getCheckedRef.signUp" class="signup-bonus-box">
        <div class="flex items-center gap-2 whitespace-normal break-words break-all">
          <img :src="signupBonusIcon" class="w-8.5">

          <div>
            <div class="text-sys-text-body font-medium">
              {{ $t('kzPlVetAcDg03Qf4im4zf') }}
            </div>
            <div class="flex items-center gap-1 whitespace-normal break-words break-all">
              <TCurrencyIcon v-if="getSignUpBonusAmountProps?.amount?.show" :symbol="currency" size="14px" />
              <span class="text-sys-text-head font-semibold">{{ getSignUpBonusAmountProps?.amount?.text || '-' }}</span>
            </div>
          </div>
        </div>
        <div class="divider-h-gradual !my-2.5" />
        <div class="flex items-center justify-between gap-4 whitespace-normal break-words break-all">
          <div class="text-sys-text-body font-medium">
            {{ $t('1a3c5B31SaClVcgfXl0sp') }}:
          </div>
          <div class="flex items-center whitespace-normal break-words break-all">
            <TCurrencyIcon v-if="getSignUpBonusAmountProps?.minDeposit?.show" class="mr-1" :symbol="currency" size="14px" />
            <span class="text-yellow-500 font-semibold">{{ getSignUpBonusAmountProps?.minDeposit?.text || '-' }}</span>
            <!-- <i class="i-ri:question-line ml-1.5 h-4.5 w-4.5 shrink-0 cursor-pointer text-sys-text-body" @click="openSignUpBonusPoup" /> -->
          </div>
        </div>
        <div class="mt-2 w-full border-(1px sys-layer-e solid) rounded-lg px-3 py-2 text-center">
          <Countdown
            class="!text-sm !text-sys-text-head"
            :value="getSignUpBonusDataRef?.timeInfo.expireDate"
            @finish="onCountDownFinish('signUp')"
          >
            <template #default="{ diff, formatText }">
              <span v-if="diff.d > 0">{{ formatText(diff.d, 'd ', false) }}</span>
              <span>{{ `${formatText(diff.h, ':')}${formatText(diff.m, ':')}${formatText(diff.s)}` }}</span>
            </template>
          </Countdown>
        </div>
        <div class="absolute right-0 top-0 max-w-full flex-center rounded-bl-lg bg-yellow-500 px-1.5 py-1 text-sys-text-head">
          <i class="i-fluent-emoji-high-contrast:check-mark h-3 w-3 font-semibold" />
        </div>
      </div>
    </div>

    <TSkeleton v-if="isInitRef && getIsShowMapRef.pwa">
      <TSkeleton type="rect" width="auto" />
    </TSkeleton>

    <div v-else-if="getIsShowMapRef.pwa" class="rounded-lg bg-sys-layer-a p-3">
      <ARadio :checked="getCheckedRef.pwa" class="check-box" @change="changeRadioFn('pwa')">
        <span class="text-sys-text-head font-semibold">{{ $t('skw3ubR9nElrZwsnUauFq') }}</span>
      </ARadio>
      <div v-if="getCheckedRef.pwa" class="signup-bonus-box">
        <div class="flex items-center gap-2 whitespace-normal break-words break-all">
          <img :src="signupBonusIcon" class="w-8.5">

          <div>
            <div class="text-sys-text-body font-medium">
              {{ $t('skw3ubR9nElrZwsnUauFq') }}
            </div>
            <div class="flex items-center gap-1 whitespace-normal break-words break-all">
              <TCurrencyIcon v-if="getPwaBonusAmountProps?.show" :symbol="currency" size="14px" />
              <span class="text-sys-text-head font-semibold">{{ getPwaBonusAmountProps?.text || '-' }}</span>
            </div>
          </div>
        </div>

        <div class="mt-2 w-full border-(1px sys-layer-e solid) rounded-lg px-3 py-2 text-center">
          <Countdown
            class="!text-sm !text-sys-text-head"
            :value="getPwaBonusDataRef?.timeInfo.expireDate"
            @finish="onCountDownFinish('pwa')"
          >
            <template #default="{ diff, formatText }">
              <span v-if="diff.d > 0">{{ formatText(diff.d, 'd ', false) }}</span>
              <span>{{ `${formatText(diff.h, ':')}${formatText(diff.m, ':')}${formatText(diff.s)}` }}</span>
            </template>
          </Countdown>
        </div>
        <div class="absolute right-0 top-0 max-w-full flex-center rounded-bl-lg bg-yellow-500 px-1.5 py-1 text-sys-text-head">
          <i class="i-fluent-emoji-high-contrast:check-mark h-3 w-3 font-semibold" />
        </div>
      </div>
    </div>

    <div v-if="getIsShowMapRef.bottomTips" class="grid grid-cols-[auto_1fr] gap-1 text-sm">
      <i class="i-local:warning mt-0.5 text-base" />
      <span>
        {{ $t('rjDh22RWpcCqJlotZVf8') }}
      </span>
    </div>

    <div v-if="!hieednBottomLine" class="divider-h-gradual !m-0" />
  </div>
</template>

<style lang="scss" scoped>
.divider-v-gradual-white {
  background-image: linear-gradient(rgba(75, 85, 99, 0.1) 0%, #dddee4 50.5%, rgba(75, 85, 99, 0.1) 100%);
  --uno: 'w-[1px] mx-2 h-6';
}
.signup-bonus-box {
  --uno: 'mt-2.5 relative p-3 pt-5 rounded-lg overflow-hidden w-[70%] min-w-65 max-w-full';
  border: 1.5px solid var(--ref-color-yellow-500, #eab308);
  background: radial-gradient(84.02% 123.6% at 16.73% -9.06%, rgba(234, 179, 8, 0.2) 0%, rgba(19, 20, 22, 0.2) 68.89%),
    var(--sys-layer-d, #26272e);
}
.check-box {
  :deep(.ant-radio) {
    .ant-radio-inner {
      --uno: '!border-(1.5px sys-layer-e solid) !bg-sys-layer-d';
    }
  }
  :deep(.ant-radio-checked) {
    .ant-radio-inner {
      --uno: '!border-(1.5px brand-500 solid) !bg-sys-layer-a';
      &::after {
        --uno: '!bg-brand-500 !w-6 !h-6 -mt-3 -ml-3';
      }
    }
  }
}
</style>
